//创建用户相关的小仓库
import { defineStore } from "pinia";
//引入登录的接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
//引入数据类型
import type { loginFromData, loginResponseData, userInfoResponseData } from "@/api/user/type";
import type { UserState } from "./types/types";

// 引入深拷贝方法
import { cloneDeep } from "lodash";
//引入持久化Token的方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
//引入路由(常量路由)
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from "@/router";


// 用于过滤路由的方法
function filterAsyncRoute(asyncRoute: any, routes: any) {
    return asyncRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true;
        }
    })
}

//创建用户小仓库
let useUserStore = defineStore('User', {
    //小仓库存储数据的地方userInfoResponseData
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            menuRouters: constantRoute,//生成菜单的数组
            username: '',
            avatar: '',
            buttons: [],//存储用户是否有某一按钮
        }
    },
    //异步存储数据的地方
    actions: {
        //用户登录的方法
        async userLogin(data: loginFromData) {
            //登录请求
            let result: loginResponseData = await reqLogin(data)
            //登录成功 code==200 并得到token
            if (result.code === 200) {
                this.token = (result.data as string)
                SET_TOKEN((result.data as string))
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }

            //登录失败 code==201 得到错误信息
        },
        //获取用户信息并存储
        async userInfo() {
            let result: userInfoResponseData = await reqUserInfo()

            if (result.code === 200) {
                this.username = result.data.name;
                this.avatar = result.data.avatar;
                // 计算当前用户需要展示的异步路由
                let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes)
                // 菜单的数据
                this.menuRouters = [...constantRoute, ...userAsyncRoute, ...anyRoute];
                // 路由器只管理了常量路由:用户计算完毕后异步路由和任意路由由动态添加
                [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
                    router.addRoute(route)
                })
                // 打印当前用户的全部路由
                console.log(this.menuRouters)
                return 'ok';
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //退出登录
        async userLogout() {
            //退出登录请求
            let result: any = await reqLogout()
            // console.log(result.code)
            //目前没有Mock接口,退出登录接口(处理用户退出登录的业务,即通知服务器用户本地的唯一标识(token/cookie)失效)
            if (result.code == 200) {
                this.username = '';
                this.avatar = '';
                this.token = '';
                REMOVE_TOKEN();
                return 'ok';
            } else {
                return Promise.reject(new Error(result.message));
            }
        }
    },
    getters: {

    }
})


//对外暴露小仓库
export default useUserStore